package com.dayatang.product.webapp.action.customervisit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.struts2.convention.annotation.Result;

import com.dayatang.product.domain.Attachment;
import com.dayatang.product.domain.CustomerVisit;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.annotation.PMLog;
import com.dayatang.product.webapp.util.WordUtil;

/**
 * 文件名:CustomerVisitSubmitAction.java
 * 描述:生成客户回访
 * 创建时间:2012-6-27 下午4:10:33
 * 创建者:mluo
 * 版本号:v2.0
 */
@Result(name = "success", type = "redirect", location = "/customervisit/customer-visit-manage.action")
public class CustomerVisitSubmitAction extends BaseAction {

	private static final long serialVersionUID = 8263033513827429668L;

	private String title;
	private long[] trialIds;
	private long[] subjectIds;
	
	@PMLog(moduleName = "客户回访", option = "生成客户回访")
	public String execute() throws Exception {
		if (title != null && trialIds.length > 0 && subjectIds.length > 0) {
			CustomerVisit customerVisit = productApplication.createCustomerVisit(title, trialIds, subjectIds);
			productApplication.saveVisitHelpAttachment(customerVisit, createAttachment(customerVisit));
		}
		return SUCCESS;
	}
	
	private Attachment createAttachment(CustomerVisit customerVisit) throws IOException {
		String fileName = getCurrentDate() + "客户回访帮助文档.doc";
		String root = getUploadDir() + "/customerVisit/id" + customerVisit.getId() + "/";
		checkFileDir(root,fileName);
		Attachment attachment = new Attachment();
		attachment.setFileName(fileName);
		attachment.setPath(root + fileName);
		attachment.setCreated(new Date());
		createWord(customerVisit,root + fileName);
		return attachment;
	}
	
	private void checkFileDir(String root,String fileName) {
		File uploadFile = new File(root, fileName);
		if (!uploadFile.getParentFile().exists()) {
			uploadFile.getParentFile().mkdirs();
		}
	}
	
	private void createWord(CustomerVisit customerVisit, String path) throws IOException {
		XWPFDocument doc = WordUtil.createWord(getCurrentDate(), customerVisit.getDifferentSubject(), customerVisit.getVisits());
		FileOutputStream out = new FileOutputStream(path);  
		doc.write(out);
		out.close();  
	}
	
	private String getCurrentDate() {
		Date today = new Date();
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		return f.format(today);
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setTrialIds(long[] trialIds) {
		this.trialIds = trialIds;
	}

	public void setSubjectIds(long[] subjectIds) {
		this.subjectIds = subjectIds;
	}
	
}
